package com.lei.sort;

import com.lei.datastructure.heep.MaxHeep;
import com.lei.linearsearch.ArrayGenerator;

/**
 * @Author LeiXiaoLei
 * @Date 2022/8/19 10:44
 * @Version 1.0
 */
public class HeapSort {
    private HeapSort() {
    }

    public static <E extends Comparable<E>> void sort(E[] data) {
        if (data.length <= 1) return;
        for (int i = (data.length - 2) / 2; i >= 0; i--)
            siftDown(data, i, data.length);
        for (int i = data.length - 1; i >= 0; i--) {
            swap(data, 0, i);
            siftDown(data, 0, i);
        }
    }

    private static <E extends Comparable<E>> void siftDown(E[] data, int k, int n) {
        while (2 * k + 1 < n) {
            int j = 2 * k + 1;
            if (j + 1 < n && data[j + 1].compareTo(data[j]) > 0) j++;
            // data[j] 是 leftChild rightChild 中最大值
            if (data[k].compareTo(data[j]) >= 0) break;
            swap(data, k, j);
            k = j;
        }
    }

    public static <E extends Comparable<E>> void swap(E[] arr, int i, int j) {
        E t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static <E extends Comparable<E>> void sort2(E[] data) {
        MaxHeep<E> maxHeep = new MaxHeep<>(data);
        for (int i = data.length - 1; i >= 0; i--)
            data[i] = maxHeep.extractMax();
    }

    public static void main(String[] args) {
        int[] dataSize = {10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
        for (int n : dataSize) {
            Integer[] arr = ArrayGenerator.generatorRandomArray(n, n);
            SortingHelper.sortTest(HeapSort.class, arr);
        }
    }
}


